# coding:utf-8
import sys

from PyQt6.QtGui import QTextCursor
from PyQt6.QtWidgets import QApplication, QMainWindow, QTextEdit, QPushButton
import logging


class LogWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.pushButton = QPushButton('Clear', self)
        self.pushButton.clicked.connect(lambda: logging.info('Clear log'))
        self.textEdit = QTextEdit(self)
        self.setCentralWidget(self.textEdit)
        self.resize(400, 300)
        self.setWindowTitle('Log Viewer')
        self.pushButton.raise_()

    def initUI(self):
        # 配置日志处理器，将日志输出到文本编辑器
        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
        handler = logging.StreamHandler(self)  # 使用StreamHandler将日志输出到文件对象
        handler.setFormatter(logging.Formatter('%(message)s'))
        logging.getLogger().addHandler(handler)

    def write(self, text):
        """将日志写入QTextEdit"""
        self.textEdit.append(text)
        self.textEdit.moveCursor(QTextCursor.MoveOperation.End)  # 滚动到底部


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = LogWindow()
    window.show()
    sys.exit(app.exec())
